<template>
  <div class="app-container">
    <div class="fd-nav-content">
      <section class="dingflow-design">
        <div class="zoom">
          <div class="zoom-out" :class="nowVal == 50 && 'disabled'" @click="zoomSize(1)"></div>
          <span>{{ nowVal }}%</span>
          <div class="zoom-in" :class="nowVal == 300 && 'disabled'" @click="zoomSize(2)"></div>
        </div>
        <div class="drag-container" ref="dragContainer">
          <div class="box-scale" 
               :style="`transform: scale(${nowVal / 100}) translate(${translatePos.x}px, ${translatePos.y}px);`"
               ref="boxScale">
            <NodeWrap v-model:nodeConfig="nodeConfig" ref="nodeWrapRef"/>
            <div class="end-node">
              <div class="end-node-circle"></div>
              <div class="end-node-text">流程结束</div>
            </div>
          </div>
        </div>
      </section>
    </div>
    <promoterDrawer/>
    <approverDrawer/>
    <copyerDrawer/>
    <conditionDrawer/>
  </div>
</template>

<script setup>
import NodeWrap from "../workflow/components/nodeWrap.vue"
import { ref, onMounted, watch, nextTick } from "vue";
import promoterDrawer from "../workflow/components/drawer/promoterDrawer.vue";
import approverDrawer from "../workflow/components/drawer/approverDrawer.vue";
import copyerDrawer from "../workflow/components/drawer/copyerDrawer.vue";
import conditionDrawer from "../workflow/components/drawer/conditionDrawer.vue";
import { useFlowStore } from "../workflow/stores/flow";

let tipList = ref([]);
let nowVal = ref(100);
let nodeConfig = ref({
  "nodeName": "发起人",
  "type": 0,
  "id": "root",
  "formPerms": {},
  "nodeUserList": [],
  "childNode": {}
});

// 拖拽相关变量
const dragContainer = ref(null);
const boxScale = ref(null);
const nodeWrapRef = ref(null); // 修改为不同的名称
const isDragging = ref(false);
const startPos = ref({ x: 0, y: 0 });
const translatePos = ref({ x: 0, y: 0 });

let props = defineProps({
  nodeConfigObj: {
    type: String,
    default: ''
  }
});

watch(() => props.nodeConfigObj, (val) => {
  nodeConfig.value = val
  nextTick(() => {
    centerNodes();
  });
});

// 居中节点函数
const centerNodes = () => {
  if (!dragContainer.value || !boxScale.value || !nodeWrapRef.value) return;

  // 获取容器和内容的尺寸
  const containerRect = dragContainer.value.getBoundingClientRect();
  const containerWidth = containerRect.width;
  const containerHeight = containerRect.height;

  // 获取节点内容的实际尺寸
  const nodesRect = nodeWrapRef.value.$el.getBoundingClientRect();
  const nodesWidth = nodesRect.width;
  const nodesHeight = nodesRect.height;

  // 计算居中位置
  const centerX = (containerWidth - nodesWidth * (nowVal.value / 100)) / 2;
  const centerY = (containerHeight - nodesHeight * (nowVal.value / 100)) / 2;

  // 设置位置
  translatePos.value = {
    x: centerX,
    y: centerY
  };

  // 应用变换
  boxScale.value.style.transform = `scale(${nowVal.value / 100}) translate(${translatePos.value.x}px, ${translatePos.value.y}px)`;
};

const reErr = ({childNode}) => {
  if (childNode) {
    let {type, error, nodeName, conditionNodes} = childNode;
    if (type == 1 || type == 2) {
      if (error) {
        tipList.value.push(nodeName + " 未设置人员");
      }
      reErr(childNode);
    } else if (type == 3) {
      reErr(childNode);
    } else if (type == 4) {
      reErr(childNode);
      for (var i = 0; i < conditionNodes.length; i++) {
        if (conditionNodes[i].error) {
          tipList.value.push('请设置'+conditionNodes[i].nodeName+'的条件');
        }
        reErr(conditionNodes[i]);
      }
    }
  } else {
    childNode = null;
  }
};

let store = useFlowStore();

watch(() => nodeConfig.value, (v) => {
  store.setStep3(v)
}, {deep: true});

const getProcessData = async () => {
  return nodeConfig.value
};

// 初始化拖拽功能
const initDrag = () => {
  if (!dragContainer.value || !boxScale.value) return;

  const container = dragContainer.value;
  const box = boxScale.value;

  // 鼠标按下事件
  const onMouseDown = (e) => {
    if (e.button !== 0) return; // 只响应左键
    isDragging.value = true;
    startPos.value = {
      x: e.clientX - translatePos.value.x,
      y: e.clientY - translatePos.value.y
    };
    
    // 设置鼠标样式
    container.style.cursor = 'grabbing';
    box.style.cursor = 'grabbing';
  };

  // 鼠标移动事件
  const onMouseMove = (e) => {
    if (!isDragging.value) return;
    
    translatePos.value = {
      x: e.clientX - startPos.value.x,
      y: e.clientY - startPos.value.y
    };
    
    box.style.transform = `scale(${nowVal.value / 100}) translate(${translatePos.value.x}px, ${translatePos.value.y}px)`;
  };

  // 鼠标抬起事件
  const onMouseUp = () => {
    isDragging.value = false;
    container.style.cursor = 'grab';
    box.style.cursor = 'default';
  };

  // 添加事件监听
  container.addEventListener('mousedown', onMouseDown);
  document.addEventListener('mousemove', onMouseMove);
  document.addEventListener('mouseup', onMouseUp);

  // 初始化样式
  container.style.cursor = 'grab';
  box.style.transition = 'transform 0.1s ease';
  
  // 返回清理函数
  return () => {
    container.removeEventListener('mousedown', onMouseDown);
    document.removeEventListener('mousemove', onMouseMove);
    document.removeEventListener('mouseup', onMouseUp);
  };
};

// 缩放功能
const zoomSize = (type) => {
  if (type == 1) {
    if (nowVal.value == 50) return;
    nowVal.value -= 10;
  } else {
    if (nowVal.value == 300) return;
    nowVal.value += 10;
  }
  
  // 更新transform样式
  if (boxScale.value) {
    boxScale.value.style.transform = `scale(${nowVal.value / 100}) translate(${translatePos.value.x}px, ${translatePos.value.y}px)`;
  }
};

const validate = (f) => {
  tipList.value = [];

  if(nodeConfig.value.childNode==undefined||nodeConfig.value.childNode.id===undefined){
    tipList.value=['请完善流程节点']
  }

  reErr(nodeConfig.value);
  if (tipList.value.length != 0) {
    f(false, tipList.value)
    return
  }
  f(true)
}

defineExpose({validate, getProcessData});

onMounted(() => {
  nextTick(() => {
    initDrag();
    // 初始化时居中节点
    centerNodes();
  });
});
</script>

<style scoped>
@import "../workflow/css/workflow.css";

.error-modal-list {
  width: 455px;
}

/* 拖拽容器样式 */
.drag-container {
  width: 100%;
  height: calc(100vh - 100px); /* 根据实际布局调整 */
  overflow: hidden;
  position: relative;
  background-color: #f5f5f7;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}

.box-scale {
  transform-origin: 0 0;
  position: absolute;
  left: 0;
  top: 0;
  padding: 20px;
}

/* 缩放控件样式 */
.zoom {
  position: absolute;
  right: 20px;
  top: 20px;
  z-index: 10;
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 5px 10px;
}

.zoom-out, .zoom-in {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  user-select: none;
}

.zoom-out:before {
  content: "-";
  font-size: 18px;
}

.zoom-in:before {
  content: "+";
  font-size: 18px;
}

.zoom-out.disabled, .zoom-in.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.zoom span {
  margin: 0 10px;
  font-size: 14px;
  min-width: 40px;
  text-align: center;
}
</style>
